<script setup>
import MessageItem from './MessageItem.vue';
import useChatStore from '@/stores/chat';
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue';
import { CODE } from '@/api/constants';
import { ElMessage } from 'element-plus';

defineProps({
    bottomPadding: {
        type: Number,
        required: false,
        default: 0
    }
})

// 当前聊天记录
const currChat = useChatStore()
onMounted(()=>{
    currChat.registerOnList((resp)=>{
        if (resp.code != CODE.OK)
        ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 3000
        })
    })
})
onUnmounted(()=>{
    currChat.unregisterOnList()
})

// 监控新信息到来，滚动到最新信息位置
const scrollbarRef = ref()
watch(
    () => currChat.messages.length,
    async (newLen, oldLen) => {
        await nextTick()
        const wrapper = scrollbarRef.value?.$el?.querySelector('.el-scrollbar__wrap')
        if (wrapper) {
            scrollbarRef.value.setScrollTop(wrapper.scrollHeight)
        }
    },
    { flush: 'post' }
);
</script>

<template>
    <el-scrollbar ref="scrollbarRef" height="100%">
        <MessageItem v-for="msg in currChat.messages" :key="msg.id" :msg="msg"></MessageItem>
        <div class="bottom-padding-class" :style="{height: `${bottomPadding}px`}" />
    </el-scrollbar>
</template>

<style scoped>
.bottom-padding-class {
    width: 100%;
}
</style>